package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.common.model.SecurityUsers;
import com.powernode.entity.User;
import com.powernode.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getLoginAct, username)
        );
        //判断用户是否为空
        if(ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //封装安全用户对象
        SecurityUsers securityUser = new SecurityUsers();
        securityUser.setId(user.getId());
        securityUser.setLoginAct(user.getLoginAct());
        securityUser.setLoginPwd(user.getLoginPwd());
        securityUser.setPhone(user.getPhone());
        securityUser.setEmail(user.getEmail());
        securityUser.setName(user.getName());
        securityUser.setAccountNoExpired(user.getAccountNoExpired());
        securityUser.setCredentialsNoExpired(user.getCredentialsNoExpired());
        securityUser.setAccountNoLocked(user.getAccountNoLocked());
        securityUser.setAccountEnabled(user.getAccountEnabled());
        securityUser.setCreateTime(user.getCreateTime());
        securityUser.setCreateBy(user.getCreateBy());
        securityUser.setEditTime(user.getEditTime());
        securityUser.setEditBy(user.getEditBy());
        securityUser.setLastLoginTime(user.getLastLoginTime());

        return securityUser;
    }
}
